const { resolve } = require('path')
const cssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin')
const HtmlWebpackPlugin = require('Html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

process.env.NODE_ENV = 'development';

module.exports = {
  // 1、入口
  entry: './src/main.js',
  // 2、出口
  output: {
    filename: 'js/index.js',
    path: resolve(__dirname, 'build')
  },
  // 3、loader
  module: {
    rules: [
      // css
      {
        test: /\.css$/i,
        use: [
          MiniCssExtractPlugin.loader, // npm i mini-css-extract-plugin -D
          'css-loader',
          // 兼容
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  ['postcss-preset-env'],
                ],
              },
            },
          },
        ],
      },
      // less
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          // 兼容
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  ['postcss-preset-env'],
                ],
              },
            },
          },
          'less-loader'
        ]
      },
      // img
      {
        test: /\.(gif|pen|jpg|jpge)$/i,
        loader: 'url-loader',
        options: {
          limit: 8 * 1024,
          name: '[hash:10].[ext]',
          esModule: false,
          outputPath: 'image'
        }
      },
      // html
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      // js
      // eslint
      /* {
        test: /\.js$/,
        exclude: /node_modules/, // 排除第三方库
        enforce:'pre', // 优先执行
        loader: 'eslint-loader',
        options: {
          // 自动修复eslint错误
          fix: true,
        },
      }, */
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,  // 排除第三方库
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'], // 预设：告诉babel怎么样做兼容性处理
            plugins: ['@babel/plugin-proposal-object-rest-spread']
          }
        }
      },
      // media
      {
        exclude: /\.(html|css|js|less)$/,
        loader: 'file-loader',
        options: {
          name: '[hash:10].[ext]',
          // outputPath: 'media'
        }
      }
      // to do...
    ]
  },
  // 4、插件
  plugins: [
    // css压缩
    new cssMinimizerWebpackPlugin(),
    // html 打包压缩
    new HtmlWebpackPlugin({
      template: './src/public/index.html',
      minify: {
        collapseWhitespace: true,
        removeComments: true
      }
    }),
    // 提取css
    new MiniCssExtractPlugin({
      filename: 'css/index.css'
    })
  ],
  // 5、环境
  mode: 'production'
}